<?php

class UserModel extends Model{
	protected $Id;
	protected $Username;
	protected $Name;
	protected $Password;
	protected $Email;
	protected $Is_teacher;
	protected $Info;
	protected $Regtime;
	protected $School;
	protected $Classyear;
	protected $Birthdate;
		
	function SetUsername($username){
		return $this->Username = $username;
	}
	
	function GetUsername(){
		return $this->Username;
	}
	
	function SetName($name){
		return $this->Name = $name;
	}
	
	function GetName(){
		return $this->Name;
	}
	
	function SetPassword($password){
		return $this->Password = sha1($password);
	}
	
	function SetEmail($Email){
		return $this->Email = $Email;
	}
	
	function GetEmail(){
		return $this->Email;
	}
	
	function SetIs_teacher($Is_teacher){
		return $this->Is_teacher = $Is_teacher;
	}
	
	function GetIs_teacher(){
		return $this->Is_teacher;
	}
	
	function SetInfo($Info){
		return $this->Info = $Info;
	}
	
	function GetInfo(){
		return $this->Info;
	}	
	
	function SetId($Id){
		return $this->Id = $Id;
	}
	
	function GetId(){
		return $this->Id;
	}
	
	function SetRegtime($regtime){
		return $this->Regtime = $regtime;
	}
	
	function GetRegtime(){
		return $this->Regtime;
	}
	
	function SetSchool($school){
		return $this->School = $school;
	}
	
	function GetSchool(){
		return $this->School;
	}
	
	function SetClassyear($classyear){
		return $this->Classyear = $classyear;
	}
	
	function GetClassyear(){
		return $this->Classyear;
	}
	
	function SetBirthdate($birthdate){
		return $this->Birthdate = $birthdate;
	}
	
	function GetBirthdate(){
		return $this->Birthdate;
	}
	
	function Validate(){
		$errors =  array();
		if((strlen($this->Username)) < 3 ){
			$errors['username'] = "A felhasználónévnek legalább 3 karaktert kell tartalmaznia!";
		}
		if(false === filter_var($this->Email, FILTER_VALIDATE_EMAIL)){
            $errors['email'] = "Hibás e-mail!";
        } 
		if((strlen($this->Name)) < 3 ){
			$errors['name'] = "A névnek legalább 3 karaktert kell tartalmaznia!";
		} 
		//$errors[3] a password
		if((strlen($this->School)) < 3 ){
			$errors['school'] = "Az iskolának legalább 3 karaktert kell tartalmaznia!";
		} 
		if(!(is_numeric ($this->Classyear))){
			$errors['class'] = "Rossz karaktereket tartalmaz az évfolyam!";
		}
		if((strlen($this->Birthdate)) != 10 ){
			$errors['date'] = "Hiányzó születési dátum!";
		} 
		return $errors;
	}
	
	function InsertUserToSql(){
		$error = $this->Validate();
		if(count($error) > 0 ){
			return $error;    
		}
		else{
			$stmt = $this->db->sqldb->prepare("INSERT INTO user (username, name, password, email, regtime, school, classyear, birthdate) VALUES (:username, :name,    
				:password, :email, :regtime, :school, :classyear, :birthdate)");
			$stmt->bindParam(':username', $this->Username);
			$stmt->bindParam(':name', $this->Name);
			$stmt->bindParam(':password', $this->Password);
			$stmt->bindParam(':email', $this->Email);
			$stmt->bindParam(':regtime', date('Y-m-d H:i:s'));
			$stmt->bindParam(':school', $this->School);
			$stmt->bindParam(':classyear', $this->Classyear);
			$stmt->bindParam(':birthdate', $this->Birthdate);
			$stmt->execute();
			$arr = array();
			$arr = $stmt->errorInfo();
			return $arr;
		}
	}

	function GetIdFromSQL($name, $pass){
		$temp = $this->db->query("SELECT id FROM user WHERE name= ? AND password= ?", array($name, $pass), $fetch = FALSE, $bindType = TRUE);
		return $temp;
	}
	
	function GetIdFromSQLByEmail($email){
		$temp = $this->db->query("SELECT id FROM user WHERE email= ?", array($email), $fetch = FALSE, $bindType = TRUE);
		return $temp;
	}

	function SelectUserFromSql($id){
		$temp = $this->db->query("SELECT * FROM user WHERE id= ?", array($id), $fetch = FALSE, $bindType = TRUE);
		$this->Id = $temp[0]['id'];
		$this->Username = $temp[0]['username'];
		$this->Name = $temp[0]['name'];
		$this->Email = $temp[0]['email'];
		$this->Info = $temp[0]['info'];
		$this->Regtime = $temp[0]['regtime'];
		$this->Birthdate = $temp[0]['birthdate'];
		$this->Is_teacher = $temp[0]['is_teacher'];
		$this->School = $temp[0]['school'];
		$this->Classyear = $temp[0]['classyear'];
		return $temp;
	}
	
	function SelectAllUserFromSql(){
		$temp = $this->db->query("SELECT * FROM user", array($id), $fetch = FALSE, $bindType = TRUE);
		return $temp;
	}
	
	function UpdateUserInSql(){
		$error = $this->Validate();
		if(count($error) > 0 ){
			return $error;    
		}
		else{
			$temp = $this->db->query('UPDATE user SET username=?, name=?, email=?, info=?, school=?, classyear=?, birthdate=? WHERE id= ?', array($this->Username, $this->Name, $this->Email, $this->Info, $this->School, $this->Classyear, $this->Birthdate, $this->Id), $fetch = FALSE, $bindType = TRUE);
		}
	}
	
	function CheckLogin(){   
		$temp = $this->db->query("SELECT username, password, id, is_teacher FROM user
			WHERE username = ? AND password = ?", array($this->Username, $this->Password), $fetch = FALSE, $bindType = TRUE);
		if(!empty($temp[0]['username'])){ 
			$this->Id = $temp[0]['id'];
			$this->Is_teacher = $temp[0]['is_teacher'];
			$_SESSION['username'] = $this->Username;
			$_SESSION['user_id'] = $this->Id;
			$_SESSION['is_teacher'] = $this->Is_teacher;
			return NULL;
		}
		else {return '<script type="text/javascript">alert("Hibás felhasználónév vagy jelszó!"); window.location = "?q=default/index"</script>';}
	}
	
	function Score($id){
		$temp = $this->db->query('SELECT user.name AS user,answer.is_correct,answer.description,task.number,task.score,task.is_checkbox,task.correct_checkbox,task_sheet.total_score,task_sheet.name,task_sheet.id FROM user,user_answer,answer,task,task_sheet WHERE user.id=? AND user_answer.user_id=user.id AND user_answer.answer_id=answer.id AND answer.task_id=task.id AND task.sheet_id=task_sheet.id ORDER BY number', array($id), $fetch = FALSE, $bindType = TRUE);	
	
		/*foreach($temp2 as $element){
			$temp[(int)$element['task_sheet_id']]=array(0 => $element['score'],
																						1 => $element['task_sheet.name'], 
																						2 => $element['max']);
		}
		var_dump($temp);*/
		return $temp;
	}
	
	function ScoreUploaded($id){
		$temp2 = $this->db->query('SELECT scores.user_id, scores.tasksheet_id,  scores.score, task_sheet.name, task.score AS max FROM (scores INNER JOIN task_sheet on scores.tasksheet_id=task_sheet.id)  INNER JOIN task on task.sheet_id=task_sheet.id WHERE user_id=?', array($id));
		return $temp2;
	}
	
	function ScoreAll(){
		$temp = $this->db->query("SELECT user.id,user.email,user.name AS user,user_answer.user_id,answer.is_correct,task.is_checkbox,task.total_checkbox,task.correct_checkbox,task.score FROM user_answer,answer,task,user WHERE user_answer.answer_id=answer.id AND answer.task_id=task.id AND user_answer.user_id=user.id", array(), $fetch = FALSE, $bindType = TRUE);
		return $temp;
	}
	
	function Logout(){
		session_unset();
		session_destroy();
	}
	
	function GeneratePasswordResetLink(){
		$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
		$length = 30;
		// Generate a random character string
		// Length of character list
		$chars_length = (strlen($chars) - 1);
		// Start our string
		$string = $chars{rand(0, $chars_length)};
		// Generate random string
		for ($i = 1; $i < $length; $i = strlen($string)){
			// Grab a random character from our list
			$r = $chars{rand(0, $chars_length)}; 
			// Make sure the same two characters don't appear next to each other
			if ($r != $string{$i - 1}) $string .=  $r;
		}
		// Return the string
		return $string;
	}
	
	function InsertPasswordResetLink($id, $link){
		$stmt = $this->db->sqldb->prepare("INSERT INTO reset_email (user_id, link) VALUES (:user_id, :link)");
		$stmt->bindParam(':user_id', $id);
		$stmt->bindParam(':link', $link);
		$stmt->execute();
		$arr = array();
		$arr = $stmt->errorInfo();
		return $arr;
	}
	
	function IsThisAResetLink($link){
		$temp = $this->db->query("SELECT user_id FROM reset_email WHERE link = ?", array($link), $fetch = FALSE, $bindType = TRUE);
		return $temp;
	}
	
	function DeleteResetLink($link){
		$temp = $this->db->query("DELETE FROM reset_email WHERE link = ?", array($link), $fetch = FALSE, $bindType = TRUE);
	}
	
	function UpdatePrivilegeInSql($data){
		try{
			foreach ($data as $key => $value){
				$temp = $temp.'UPDATE `user` SET `is_teacher` = \''.$data[$key]['is_teacher'].'\' WHERE `id` = '.$key.'; ';
			}
			$stmt = $this->db->sqldb->prepare($temp);
			$stmt->execute();
		}catch(PDOException $error){
			$db->rollBack();
		}
	}
	
	function UpdatePasswordInSql($pass, $id){
		$temp = $this->db->query('UPDATE user SET password=? WHERE id= ?', array($pass, $id), $fetch = FALSE, $bindType = TRUE);
	}
	
}
